package horncomb.bpm.process.def.activity;

import java.util.List;

import org.springframework.util.Assert;

import horncomb.bpm.BpmContextHolder;
import horncomb.bpm.process.core.ExecutionContext;
import horncomb.bpm.process.core.LeavableState;
import horncomb.bpm.process.core.Token;
import horncomb.bpm.process.core.Transition;
import horncomb.bpm.process.instance.DefaultExcutionContext;
import horncomb.bpm.process.instance.TokenCreator;

/**
 * @author Daniel
 */
public class ParallelSplitStateDefinition extends AbstractActivityDefinition {
	private static final long serialVersionUID = -1950153743378542824L;
	protected TokenCreator tokenCreator = null;

	/**
	 * @param id
	 */
	public ParallelSplitStateDefinition(String id) {
		super(id);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void doEnteringAction(ExecutionContext context) {
		if (context.getToken().getState() instanceof LeavableState) {
			List<Transition> ts = ((LeavableState) context.getToken()
					.getState()).getLeavingTransitions();
			for (Transition t : ts) {
				Token subToken = BpmContextHolder.getContext()
						.getProcessManagementService().invokeCreateToken(
								context.getToken().getEntity()
										.getProcessInstanceId(),
								context.getToken(), context.getContextModel(),
								this.tokenCreator);
				ExecutionContext subCtx = new DefaultExcutionContext(subToken,
						context.getContextModel());
				t.transit(subCtx);
			}
		}
	}

	/**
	 * @param tokenCreator
	 *            the tokenCreator to set
	 */
	public void setTokenCreator(TokenCreator tokenCreator) {
		Assert.notNull(tokenCreator);
		this.tokenCreator = tokenCreator;
	}
}
